package com.xin.di.uav.applet.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xin.di.uav.applet.mapper.*;
import com.xin.di.uav.applet.rest.*;
import com.xin.di.uav.applet.service.IOrderInfoService;
import com.xin.di.uav.common.awt.JwtUtil;
import com.xin.di.uav.common.enums.*;
import com.xin.di.uav.common.exception.BusinessException;
import com.xin.di.uav.common.request.order.*;
import com.xin.di.uav.common.utils.*;
import com.xin.di.uav.mapper.BillMapper;
import com.xin.di.uav.po.Bill;
import com.xin.di.uav.po.OrderCommodity;
import com.xin.di.uav.po.OrderMapper;
import com.xin.di.uav.user.entity.UserCompany;
import com.xin.di.uav.user.mapper.UserMapper;
import com.xin.di.uav.user.order.po.OrderPO;
import com.xin.di.uav.user.order.po.TaskStatusLog;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author LTQ
 * @since 2023-05-08
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implements IOrderInfoService {
    private final static Logger logger = LoggerFactory.getLogger(OrderInfoServiceImpl.class);

    @Autowired
    private OrderMapper orderInfoMapper;


    @Autowired
    private UserCompanyMapper userCompanyMapper;


    @Autowired
    private TaskStatusLogRest taskStatusLogRest;

    @Autowired
    private BillMapper billMapper;


    @Autowired
    private OrderCommodityRest orderCommodityRest;

    @Autowired
    private RedisTemplate redisTemplate;


    @Value("${wx.delivery-start-template-id:Qy_sG7jpaXYE_GApiS21Ozj4m7L8dZo334Es-dKtbRU}")
    private String deliveryStartTemplateId;


    @Autowired
    private CommodityMapper commodityMapper;


    @Override
    public void add(OrderInfoAddRequest orderInfoAddRequest) {
        OrderPO orderInfo = BeanUtil.copyProperties(orderInfoAddRequest, OrderPO.class);
        this.insert(orderInfo);
    }


    @Override
    public List<OrderPO> getOrders(Integer page, Integer size) {
        String userId = JwtUtil.getUserId();
        QueryWrapper<OrderPO> orderInfoQueryWrapper = new QueryWrapper<>();
        Page<OrderPO> orderInfoPage = new Page<>(page, size);
        orderInfoQueryWrapper.lambda().eq(OrderPO::getUserId, userId).orderByDesc(OrderPO::getCreatedAt);
        IPage<OrderPO> orderInfoIPage = this.selectPage(orderInfoPage, orderInfoQueryWrapper);
        return orderInfoIPage.getRecords();
    }


    @Override
    public Long getTotal(@RequestParam(required = false) String tcWaybillNo, @RequestParam(required = false) String tradeNo, @RequestParam(required = false) Integer type, @RequestParam(required = false) Integer platformCode, String enterpriseId, Integer payStatus, Date startTransactionTime, Date endTransactionTime) {
        List<OrderPO> orderInfoList;
        QueryWrapper<OrderPO> orderInfoQueryWrapper = new QueryWrapper<>();
        List<String> ids;
        QueryWrapper<Bill> billQueryWrapper = new QueryWrapper<>();
        String userId = getUserId(enterpriseId);
        if (StringUtils.isNotBlank(tcWaybillNo) || StringUtils.isNotBlank(tradeNo) || platformCode != null) {
            if (!ObjectUtils.isEmpty(tcWaybillNo)) {
                orderInfoQueryWrapper.like("tc_waybill_no", tcWaybillNo);
            }
            if (!ObjectUtils.isEmpty(tradeNo)) {
                orderInfoQueryWrapper.like("trade_no", tradeNo);
            }
            if (!ObjectUtils.isEmpty(platformCode)) {
                orderInfoQueryWrapper.eq("platform_code", platformCode);
            }
            orderInfoList = this.selectList(orderInfoQueryWrapper);
            if (CollectionUtils.isEmpty(orderInfoList)) {
                return 0L;
            }
            ids = orderInfoList.stream().map(orderInfo -> orderInfo.getId()).collect(Collectors.toList());
            billQueryWrapper.in("order_id", ids);
        }
        if (!ObjectUtils.isEmpty(type)) {
            billQueryWrapper.eq("type", type);
        }
        if (!ObjectUtils.isEmpty(startTransactionTime)) {
            billQueryWrapper.ge("create_time", startTransactionTime);
        }
        if (!ObjectUtils.isEmpty(payStatus)) {
            billQueryWrapper.eq("pay_status", payStatus);
        }
        if (!ObjectUtils.isEmpty(userId)) {
            billQueryWrapper.eq("user_id", userId);
        }
        if (!ObjectUtils.isEmpty(endTransactionTime)) {
            billQueryWrapper.le("create_time", endTransactionTime);
        }

        return billMapper.selectCount(billQueryWrapper);
    }


    private String getUserId(String enterpriseId) {
        UserCompany userCompany = null;
        String userId = null;
        if (StringUtils.isNotBlank(enterpriseId)) {
            userCompany = userCompanyMapper.selectOne(new QueryWrapper<UserCompany>().eq("enterprise_id", enterpriseId));
        }
        if (!ObjectUtils.isEmpty(userCompany)) {
            userId = userCompany.getUserId();
        }
        return userId;
    }

    @Override
    public int insert(OrderPO entity) {
//        String senderDoorplate = entity.getSenderDoorplate();
//        String receiverDoorplate = entity.getReceiverDoorplate();
//        String senderTel = entity.getSenderTel();
//        String receiverTel = entity.getReceiverTel();
//        if (!ObjectUtils.isEmpty(senderDoorplate)) {
//            senderDoorplate = phoneEncoderUtil.encryptString(senderDoorplate);
//            entity.setSenderDoorplate(senderDoorplate);
//        }
//        if (!ObjectUtils.isEmpty(receiverDoorplate)) {
//            receiverDoorplate = phoneEncoderUtil.encryptString(receiverDoorplate);
//            entity.setReceiverDoorplate(receiverDoorplate);
//        }
//        if (!ObjectUtils.isEmpty(senderTel)) {
//            senderTel = phoneEncoderUtil.encryptString(senderTel);
//            entity.setSenderTel(senderTel);
//        }
//        if (!ObjectUtils.isEmpty(receiverTel)) {
//            receiverTel = phoneEncoderUtil.encryptString(receiverTel);
//            entity.setReceiverTel(receiverTel);
//        }
        return orderInfoMapper.insert(entity);
    }

    @Override
    public List<OrderPO> selectList(Wrapper<OrderPO> queryWrapper) {
        List<OrderPO> orderInfoList = orderInfoMapper.selectList(queryWrapper);
        orderInfoList.forEach(orderInfo -> {
//            String senderDoorplate = orderInfo.getSenderDoorplate();
//            String receiverDoorplate = orderInfo.getReceiverDoorplate();
//            senderDoorplate = phoneEncoderUtil.decryptString(senderDoorplate);
//            receiverDoorplate = phoneEncoderUtil.decryptString(receiverDoorplate);
//            orderInfo.setSenderDoorplate(senderDoorplate);
//            orderInfo.setReceiverDoorplate(receiverDoorplate);
        });
        return orderInfoMapper.selectList(queryWrapper);
    }

    @Override
    public IPage<OrderPO> selectPage(Page page, Wrapper<OrderPO> queryWrapper) {
        IPage<OrderPO> orderInfoIPage = orderInfoMapper.selectPage(page, queryWrapper);
        List<OrderPO> orderInfoList = orderInfoIPage.getRecords();
        orderInfoList.forEach(orderInfo -> {
//            String senderTel = orderInfo.getSenderTel();
//            String receiverTel = orderInfo.getReceiverTel();
//
//            String receiverDoorplate = orderInfo.getReceiverDoorplate();
//
//            String senderDoorplate = orderInfo.getSenderDoorplate();
//            senderTel = phoneEncoderUtil.decryptString(senderTel);
//            receiverTel = phoneEncoderUtil.decryptString(receiverTel);
//            receiverDoorplate = phoneEncoderUtil.decryptString(receiverDoorplate);
//            senderDoorplate = phoneEncoderUtil.decryptString(senderDoorplate);
//            orderInfo.setSenderTel(senderTel);
//            orderInfo.setReceiverTel(receiverTel);
//            orderInfo.setReceiverDoorplate(receiverDoorplate);
//            orderInfo.setSenderDoorplate(senderDoorplate);
        });
        return orderInfoIPage;
    }

    @Override
    public OrderPO selectOne(Wrapper<OrderPO> queryWrapper) {
        OrderPO orderInfo = orderInfoMapper.selectOne(queryWrapper);
//        String senderTel = orderInfo.getSenderTel();
//        String receiverTel = orderInfo.getReceiverTel();
//
//        String senderDoorplate = orderInfo.getSenderDoorplate();
//        String receiverDoorplate = orderInfo.getReceiverDoorplate();
//        senderTel = phoneEncoderUtil.decryptString(senderTel);
//        receiverTel = phoneEncoderUtil.decryptString(receiverTel);
//
//        senderDoorplate = phoneEncoderUtil.decryptString(senderDoorplate);
//        receiverDoorplate = phoneEncoderUtil.decryptString(receiverDoorplate);
//        orderInfo.setSenderTel(senderTel);
//        orderInfo.setReceiverTel(receiverTel);
//
//        orderInfo.setSenderDoorplate(senderDoorplate);
//        orderInfo.setReceiverDoorplate(receiverDoorplate);
        return orderInfo;
    }


    @Override
    public void updateStatus(UpdateStatusRequest updateStatusRequest) {
        String processedBy = updateStatusRequest.getProcessedBy();
        String orderId = updateStatusRequest.getOrderId();
        Integer status = updateStatusRequest.getOrderStatus();
        if (!status.equals(RescueOrderStatusEnum.MATERIAL_PREPARATION.getStatus()) && !status.equals(RescueOrderStatusEnum.IN_TRANSIT.getStatus()) && !status.equals(RescueOrderStatusEnum.COMPLETED.getStatus())) {
            throw new BusinessException("只能将状态改为物资准备中、⽆⼈机运输中、已完成");
        }
        Date date = new Date();
        OrderPO orderInfo = orderInfoMapper.selectById(orderId);
        if (ObjectUtils.isEmpty(orderInfo)) {
            throw new BusinessException("订单不存在");
        }
        String userId = orderInfo.getUserId();
        Integer orderStatus = orderInfo.getStatus();


        if (!RescueOrderStatusEnum.WAITING_FOR_ORDER_ACCEPTANCE.getStatus().equals(orderStatus) && !RescueOrderStatusEnum.MATERIAL_PREPARATION.getStatus().equals(orderStatus) && !RescueOrderStatusEnum.IN_TRANSIT.getStatus().equals(orderStatus)) {
            throw new BusinessException("只能修改订单状态为等待平台接单、物资准备中、⽆⼈机运输中的订单");
        }
        if (!status.equals(orderStatus)) {
            if (status.equals(RescueOrderStatusEnum.MATERIAL_PREPARATION.getStatus())) {
                if (!orderStatus.equals(RescueOrderStatusEnum.WAITING_FOR_ORDER_ACCEPTANCE.getStatus())) {
                    throw new BusinessException("等待平台接单的状态才能更新为物资准备中");
                } else {
                }
            } else if (status.equals(RescueOrderStatusEnum.IN_TRANSIT.getStatus())) {
                if (!orderStatus.equals(RescueOrderStatusEnum.MATERIAL_PREPARATION.getStatus())) {
                    throw new BusinessException("物资准备中的状态才能更新为⽆⼈机运输中");
                }
            } else if (status.equals(RescueOrderStatusEnum.COMPLETED.getStatus())) {
                if (!orderStatus.equals(RescueOrderStatusEnum.MATERIAL_PREPARATION.getStatus()) && !orderStatus.equals(RescueOrderStatusEnum.IN_TRANSIT.getStatus())) {
                    throw new BusinessException("物资准备中/运输中的状态才能更新为已完成");
                }
            }
            orderInfo.setStatus(status);
            orderInfo.setUpdatedAt(date);
            orderInfoMapper.updateById(orderInfo);
            TaskStatusLog taskStatusLog = new TaskStatusLog();
            taskStatusLog.setStatus(status);
            taskStatusLog.setTaskId(orderInfo.getId());
            taskStatusLog.setProcessedBy(processedBy);
            taskStatusLog.setCreateTime(date);
            taskStatusLog.setUpdateTime(date);
            taskStatusLog.setUserId(orderInfo.getUserId());
            taskStatusLogRest.add(taskStatusLog);
            String templateId = null;
//            String accessToken = loginService.getAccessToken();
            HashMap data = new HashMap();
            String openId = (String) redisTemplate.opsForValue().get(ServicePrefixEnum.RESCUE + RedisPrefixKey.APPLET_OPENID + userId);
            //状态变更
            if (status.equals(RescueOrderStatusEnum.MATERIAL_PREPARATION.getStatus())) {
//                templateId = updateStatusTemplateId;
//                Map character_string1 = new HashMap();
//                character_string1.put("value", orderInfo.getTcWaybillNo());
//                Map phrase11 = new HashMap();
//                phrase11.put("value", RescueOrderStatusEnum.getName(status));
//                Map thing5 = new HashMap();
//                thing5.put("value", "您的无人机订单已开始准备");
//                Map date4 = new HashMap();
//                date4.put("value", DateUtil.format(orderInfo.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
//                data.put("character_string1", character_string1);
//                data.put("phrase11", phrase11);
//                data.put("thing5", thing5);
//                data.put("date4", date4);
            } else if (status.equals(RescueOrderStatusEnum.IN_TRANSIT.getStatus())) {
                templateId = deliveryStartTemplateId;
//                String placementPointId = orderInfo.getPlacementPointId();
//                String targetAddress = "";
//                if (!ObjectUtils.isEmpty(placementPointId)) {
//                    PlacementPoint placementPoint = placementPointMapper.selectById(placementPointId);
//                    if (!ObjectUtils.isEmpty(placementPoint)) {
//                        String scenicSpotId = placementPoint.getScenicSpotId();
//                        ScenicSpot scenicSpot = scenicSpotMapper.selectById(scenicSpotId);
//                        if (!ObjectUtils.isEmpty(scenicSpot)) {
//                            targetAddress = scenicSpot.getName() + "-" + placementPoint.getName();
//                        }
//                    }
//                }
//                Map thing2 = new HashMap(1);
//                if (!ObjectUtils.isEmpty(targetAddress)) {
//                    int length = targetAddress.length();
//                    if (length > 20) {
//                        targetAddress = targetAddress.substring(0, 16) + "...";
//                    }
//                    thing2.put("value", targetAddress);
//                }
//
//                Map character_string7 = new HashMap();
//                character_string7.put("value", orderInfo.getTcWaybillNo());
                Map thing1 = new HashMap();
                List<OrderCommodity> orderCommodities = orderCommodityRest.getByOrderSn(orderInfo.getOrderNo());
                if (!CollectionUtils.isEmpty(orderCommodities)) {
                    List<String> commodityIds = orderCommodities.stream().map(orderCommodity -> orderCommodity.getCommodityId()).collect(Collectors.toList());
                    String names = commodityMapper.selByIds(commodityIds).stream().map(commodity -> commodity.getName()).collect(Collectors.joining(";"));
                    if (!ObjectUtils.isEmpty(names)) {
                        int length = names.length();
                        if (length > 20) {
                            names = names.substring(0, 16) + "...";
                        }
                        thing1.put("value", names);
                    }

                }
//                Map thing5 = new HashMap();
//                thing5.put("value", "请在投送点等待商品送达");
//                data.put("character_string7", character_string7);
//                data.put("thing1", thing1);
//                data.put("thing5", thing5);
//                data.put("thing2", thing2);
            } else if (status.equals(RescueOrderStatusEnum.COMPLETED.getStatus())) {
//                String placementPointId = orderInfo.getPlacementPointId();
//                String targetAddress = "";
//                if (!ObjectUtils.isEmpty(placementPointId)) {
//                    PlacementPoint placementPoint = placementPointMapper.selectById(placementPointId);
//                    if (!ObjectUtils.isEmpty(placementPoint)) {
//                        String scenicSpotId = placementPoint.getScenicSpotId();
//                        ScenicSpot scenicSpot = scenicSpotMapper.selectById(scenicSpotId);
//                        if (!ObjectUtils.isEmpty(scenicSpot)) {
//                            targetAddress = scenicSpot.getName() + "-" + placementPoint.getName();
//                        }
//                    }
//                }
//
//                templateId = deliveryCompletedTemplateId;
//                //配送完成
//                Map character_string1 = new HashMap(1);
//                character_string1.put("value", orderInfo.getTcWaybillNo());
//                Map thing2 = new HashMap(1);
//                if (!ObjectUtils.isEmpty(targetAddress)) {
//                    int length = targetAddress.length();
//                    if (length > 20) {
//                        targetAddress = targetAddress.substring(0, 16) + "...";
//                    }
//                    thing2.put("value", targetAddress);
//                }
//                Map thing3 = new HashMap(1);
//                thing3.put("value", "您的订单已由无人机安全送达~");
//                JSONObject time4 = new JSONObject();
//                time4.put("value", sdf.format(date));
//                data.put("thing2", thing2);
//                data.put("thing3", thing3);
//                data.put("time4", time4);
//                data.put("character_string1", character_string1);
            }
//            wxAppletRest.subscribeSend(accessToken, templateId, openId, data, "packageA/pages/goodsDetail/goodsDetail?id=" + orderInfo.getId() + "&backHome=1");
        }
    }


    @Override
    public void updateStatusBySn(FlightRequest flightRequest) {
        String orderSn = flightRequest.getFyCode();
        String processedBy = "平台组";
        Integer flightStatus = flightRequest.getOrderStatus();
        Date date = new Date();
        OrderPO orderInfo = orderInfoMapper.selByFyOrderNo(orderSn);
        if (ObjectUtils.isEmpty(orderInfo)) {
            throw new BusinessException("订单不存在");
        }
        Integer orderStatus = orderInfo.getStatus();
        if (!Objects.equals(orderStatus, flightStatus)) {
            orderInfo.setStatus(flightStatus);
            orderInfo.setUpdatedAt(date);
            orderInfoMapper.updateById(orderInfo);
        }
        TaskStatusLog taskStatusLog = new TaskStatusLog();
        taskStatusLog.setStatus(flightStatus);
        taskStatusLog.setTaskId(orderInfo.getId());
        taskStatusLog.setProcessedBy(processedBy);
        taskStatusLog.setCreateTime(date);
        taskStatusLog.setUpdateTime(date);
        taskStatusLog.setUserId(orderInfo.getUserId());
        taskStatusLogRest.add(taskStatusLog);

    }

    @Override
    public void takeOffNotify(TakOffRequest takOffRequest) {
        String orderSn = takOffRequest.getFyCode();
        String processedBy = "平台组";
        Date date = new Date();
        OrderPO orderInfo = orderInfoMapper.selByFyOrderNo(orderSn);
        if (ObjectUtils.isEmpty(orderInfo)) {
            throw new BusinessException("订单不存在");
        }
        Integer orderStatus = orderInfo.getStatus();
        if (!orderStatus.equals(RescueOrderStatusEnum.COMPLETED.getStatus())) {
            Integer updateStatus = RescueOrderStatusEnum.IN_TRANSIT.getStatus();
            if (!Objects.equals(orderStatus, updateStatus)) {
                orderInfo.setStatus(updateStatus);
                orderInfo.setUpdatedAt(date);
                orderInfoMapper.updateById(orderInfo);
                TaskStatusLog taskStatusLog = new TaskStatusLog();
                taskStatusLog.setStatus(updateStatus);
                taskStatusLog.setTaskId(orderInfo.getId());
                taskStatusLog.setProcessedBy(processedBy);
                taskStatusLog.setCreateTime(date);
                taskStatusLog.setUpdateTime(date);
                taskStatusLog.setUserId(orderInfo.getUserId());
                taskStatusLogRest.add(taskStatusLog);
            }
        }
    }

    @Override
    public void landingNotify(LandingRequest landingRequest) {
        String orderSn = landingRequest.getFyCode();
        String processedBy = "平台组";
        Date date = new Date();
        OrderPO orderInfo = orderInfoMapper.selByFyOrderNo(orderSn);
        if (ObjectUtils.isEmpty(orderInfo)) {
            throw new BusinessException("订单不存在");
        }
        Integer orderStatus = orderInfo.getStatus();
        if (!orderStatus.equals(RescueOrderStatusEnum.COMPLETED.getStatus())) {
            Integer updateStatus = RescueOrderStatusEnum.DELIVERY.getStatus();
            if (!Objects.equals(orderStatus, updateStatus)) {
                orderInfo.setStatus(updateStatus);
                orderInfo.setUpdatedAt(date);
                orderInfoMapper.updateById(orderInfo);
                TaskStatusLog taskStatusLog = new TaskStatusLog();
                taskStatusLog.setStatus(updateStatus);
                taskStatusLog.setTaskId(orderInfo.getId());
                taskStatusLog.setProcessedBy(processedBy);
                taskStatusLog.setCreateTime(date);
                taskStatusLog.setUpdateTime(date);
                taskStatusLog.setUserId(orderInfo.getUserId());
                taskStatusLogRest.add(taskStatusLog);
            }
        }
    }

    @Override
    public void pickUpCodeNotify(PickUpCodeRequest pickUpCodeRequest) {
        String orderSn = pickUpCodeRequest.getFyCode();
        Date date = new Date();
        OrderPO orderInfo = orderInfoMapper.selByFyOrderNo(orderSn);
        if (ObjectUtils.isEmpty(orderInfo)) {
            throw new BusinessException("订单不存在");
        }
        orderInfo.setPickUpCode(pickUpCodeRequest.getPickUpCode());
        orderInfo.setUpdatedAt(date);
        orderInfoMapper.updateById(orderInfo);
    }


}
